package org.linlinjava.litemall.wx.web;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.CartMsg;
import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.domain.LitemallCart;
import org.linlinjava.litemall.db.domain.LitemallCommodity;
import org.linlinjava.litemall.db.service.LitemallAddressService;
import org.linlinjava.litemall.db.service.LitemallCartService;
import org.linlinjava.litemall.db.service.LitemallCommodityService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户购物车服务
 */
@RestController
@RequestMapping("/wx/cart")
//@Validated
public class WxCartController {
    private final Log log = LogFactory.getLog(WxCartController.class);

    @Autowired
    private LitemallCartService cartService;

    @Autowired
    private LitemallAddressService addressService;

    @Autowired
    private LitemallCommodityService commodityService;

    /**
     * 用户购物车信息
     *
     * @return 用户购物车信息
     */
    @GetMapping("index")
    public Object index(HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        Integer userId = Integer.parseInt(user.getUserid());
        List<CartMsg> cartMsgs =cartService.findCardByUserId(userId);
/*        for (CartMsg cartMsg : cartMsgs) {
            BigDecimal multiply = cartMsg.getCommodityPrice().multiply(new BigDecimal(cartMsg.getCommodityNum()));
            cartMsg.setTotalPrice(multiply);
        }*/
        return ResponseUtil.ok(cartMsgs);
    }

    /**
     * 加入商品到购物车
     * <p>
     * 如果已经存在购物车货品，则增加数量；
     * 否则添加新的购物车货品项。
     *
     * @return 加入购物车操作结果
     */
    @PostMapping("add")
    public Object add(@RequestBody String json,HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        Integer userId = Integer.parseInt(user.getUserid());
        int number = JacksonUtil.parseInteger(json, "number");
        Integer goodsId = JacksonUtil.parseInteger(json, "goodsId");
        LitemallCart cart = new LitemallCart(userId,goodsId,(short)number);
        //如果有为空的，则返回报错
        if (!ObjectUtils.allNotNull(number, goodsId)) {
            return ResponseUtil.badArgument();
        }
        LitemallCart existCart = cartService.queryExist(goodsId, userId);
        //如果购物车不为空
        if (existCart != null) {
            existCart.setCommodityNum((short)(existCart.getCommodityNum()+number));
            if (cartService.updateById(existCart) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
            return ResponseUtil.ok();
        }else {
            cartService.add(cart);
            return ResponseUtil.ok();
        }
    }

    /**
     * 立即购买
     * <p>
     * 和add方法的区别在于：
     * 1. 如果购物车内已经存在购物车货品，前者的逻辑是数量添加，这里的逻辑是数量覆盖
     * 2. 添加成功以后，前者的逻辑是返回当前购物车商品数量，这里的逻辑是返回对应购物车项的ID
     *
     * @return 立即购买操作结果
     */
    @PostMapping("fastadd")
    public Object fastadd(@RequestBody String json,HttpServletRequest request) {
        LitemallCart cart = new LitemallCart();
        XxlSsoUser user = (XxlSsoUser) (request.getAttribute(Conf.SSO_USER));
        Integer userId = Integer.parseInt(user.getUserid());
        Integer number = JacksonUtil.parseInteger(json, "number");
        Integer goodsId = JacksonUtil.parseInteger(json, "goodsId");
        if (!ObjectUtils.allNotNull(number, goodsId)) {
            return ResponseUtil.badArgument();
        }
        if(number <= 0){
            return ResponseUtil.badArgument();
        }
        //判断购物车中是否存在此规格商品
        LitemallCart existCart = cartService.queryExist(goodsId,userId);
        if (existCart == null) {
            cart.setId(null);
            cart.setUserId(userId);
            cartService.add(cart);
        } else {
            //取得规格的信息,判断规格库存
            int num = number;
            existCart.setCommodityNum((short) num);
            if (cartService.updateById(existCart) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
        }

        return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
    }

    /**
     * 修改购物车商品货品数量
     * @return 修改结果
     */
    @PostMapping("update")
    public Object update(@RequestBody String json) {
        Integer number = JacksonUtil.parseInteger(json, "number");
        Integer id = JacksonUtil.parseInteger(json, "id");
        LitemallCart cart = new LitemallCart();
        cart.setCommodityNum(number.shortValue());
        cart.setId(id);
        if (!ObjectUtils.allNotNull(id, number)) {
            return ResponseUtil.badArgument();
        }
        if(number <= 0){
            return ResponseUtil.badArgument();
        }

        //判断是否存在该订单
        // 如果不存在，直接返回错误
        LitemallCart existCart = cartService.findById(id);
        if (existCart == null) {
            return ResponseUtil.badArgumentValue();
        }

        existCart.setCommodityNum(number.shortValue());
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok();
    }

    /**
     * 购物车商品删除
     *
     * @return 购物车信息
     * 成功则
     * {
     * errno: 0,
     * errmsg: '成功',
     * data: xxx
     * }
     * 失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("delete")
    public Object delete(@RequestBody String json) {
        List<Integer> cartIds = JacksonUtil.parseIntegerList(json, "cartIds");
        if (cartIds == null || cartIds.size() == 0) {
            return ResponseUtil.badArgument();
        }
        try {
            for (Integer cartId : cartIds) {
                cartService.deleteById(cartId);
            }
            return ResponseUtil.ok();
        }catch (Exception e){
            System.out.println(e);
            return ResponseUtil.badArgument();
        }
    }


    /**
     * 购物车下单
     *
     * @param userId    用户ID
     * @param cartIds    购物车IDs：
     *                  如果购物车商品ID是空，则下单当前用户所有购物车商品；
     *                  如果购物车商品ID非空，则只下单当前购物车商品。
     * @param addressId 收货地址ID：
     *                  如果收货地址ID是空，则查询当前用户的默认地址。
     *                  如果优惠券ID是空，则自动选择合适的优惠券。
     * @return 购物车操作结果
     */
    @GetMapping("checkout")
    public Object checkout(@LoginUser Integer userId, List<Integer> cartIds, Integer addressId) {
        // 收货地址
        LitemallAddress checkedAddress = null;
        if (addressId == null || addressId.equals(0)) {
            checkedAddress = addressService.findDefault(userId);
            // 如果仍然没有地址，则是没有收货地址
            // 返回一个空的地址id=0，这样前端则会提醒添加地址
            if (checkedAddress == null) {
                checkedAddress = new LitemallAddress();
                checkedAddress.setId(0);
                addressId = 0;
            } else {
                addressId = checkedAddress.getId();
            }

        } else {
            checkedAddress = addressService.query(userId, addressId);
            // 如果null, 则报错
            if (checkedAddress == null) {
                return ResponseUtil.badArgumentValue();
            }
        }
        // 商品价格
        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        for (Integer cartId : cartIds) {
            LitemallCart cart = cartService.findById(cartId);
            LitemallCommodity commodity = commodityService.selectById(cart.getCommodityId());
            checkedGoodsPrice = checkedGoodsPrice.add(commodity.getCommodityPrice().multiply(new BigDecimal(cart.getCommodityNum())));
        }

        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.max(new BigDecimal(0.00));

        Map<String, Object> data = new HashMap<>();
        data.put("addressId", addressId);
        data.put("cartIds", cartIds);
        data.put("checkedAddress", checkedAddress);
        data.put("goodsTotalPrice", checkedGoodsPrice);
        data.put("orderTotalPrice", orderTotalPrice);
        return ResponseUtil.ok(data);
    }

    /**
     * 根据购物车信息生成订单商品信息
     * @author Riko
     * @date 2019/11/25
     * @update 2019/11/25
     **/
    @PostMapping("find")
    public Object find(@RequestBody String msg) {
        System.out.println("msg>>>" + msg);
        List<Integer> list = JacksonUtil.parseIntegerList(msg, "idList");
        if (list == null || list.size() < 1) {
            return ResponseUtil.badArgument();
        }
        return ResponseUtil.ok(cartService.findGoods(list));
    }
}